package concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest1 {
    BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(10);

    public static void main(String[] args) { //
        BlockingQueueTest1 p = new BlockingQueueTest1();
        Thread p1 = new Thread(new BlockingQueueTest1_Producer(p), "sc-1");
        Thread p2 = new Thread(new BlockingQueueTest1_Producer(p), "sc-2");
        Thread p3 = new Thread(new BlockingQueueTest1_Producer(p), "sc-3");
        Thread c1 = new Thread(new BlockingQueueTest1_Consumer(p), "xf-1");
        Thread c2 = new Thread(new BlockingQueueTest1_Consumer(p), "xf-2");
        Thread c3 = new Thread(new BlockingQueueTest1_Consumer(p), "xf-3");
        p1.start();
        p2.start();
        p3.start();
        c1.start();
        c2.start();
        c3.start();
    }
}

class BlockingQueueTest1_Producer implements Runnable {
    BlockingQueueTest1 p;

    public BlockingQueueTest1_Producer(BlockingQueueTest1 p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " increase -- " + p.queue.size());
            try {
                p.queue.put(new Object());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

class BlockingQueueTest1_Consumer implements Runnable {
    BlockingQueueTest1 p;

    public BlockingQueueTest1_Consumer(BlockingQueueTest1 p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(Thread.currentThread().getName() + " decrease -- " + p.queue.size());
            try {
                p.queue.take();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}